package com.wh.wisdomsite.xbox.utils.properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;



/**
 * Properties工具类
 * @Package com.wh.wisdomsite.xbox.utils.properties
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
public class PropertiesTool extends PropertyPlaceholderConfigurer {


    private static final Log logger = LogFactory.getLog(PropertiesTool.class);

    private static Map<String, String> ctxPropertiesMap;

    /**
     * 重写父类方法
     * @param beanFactory 工厂
     * @param properties  属性文件
     * @throws BeansException
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties properties)throws BeansException {
        //初始化父类
        super.processProperties(beanFactory, properties);
        //初始化Map
        ctxPropertiesMap = new HashMap<String, String>();
        logger.info("processProperties->>重写父类结构");
        logger.info("processProperties->>准备读取Properties文件");
        logger.info("processProperties->>正在读取Properties文件");
        //Map存储
        for (Object key : properties.keySet()) {
            String keyStr = key.toString();
            String value = properties.getProperty(keyStr);
            ctxPropertiesMap.put(keyStr, value);
        }
        logger.info("processProperties->>读取完毕Properties文件");
    }

    /**
     * 根据Properties的key获取值
     * @param key 对应key
     * @return
     */
    public static String getProperty(String key) {
        String value = ctxPropertiesMap.get(key);
        logger.info("getProperty->>根据key获取值key：" + key);
        logger.info("getProperty->>根据key获取值value：" + value);
        return value;
    }


    /**
     * 根据Properties的key获取值
     * @param key
     * @param replaceMap
     * @return
     */
    public static String getProperties(String key, Map<String, Object> replaceMap){
        String  prop = getProperty(key);
        Iterator iterator = replaceMap.keySet().iterator();
        while (iterator.hasNext()) {
            String str = (String) iterator.next();
            if(replaceMap.get(str) == null){
                replaceMap.put(str,"");
            }
            prop = prop.replace(str, replaceMap.get(str).toString());
        }
        return prop;
    }

}
